#include "NotifyQueue.h"
#include "UserManager.h"
#include "HandleRequest.h"
#include"NotifyFactory.h"


extern UserManager user_manager;

NotifyQueue::NotifyQueue(json j) {
    try{
        this->unserialize(j);
    }
    catch(exception& e){
        syslog(LOG_ERR, "NotifyQueue unserialize error:%s", e.what());
        #ifdef DEBUG
        PRINT_ERRNO_AND_STRERROR(errno, "NotifyQueue unserialize error:%s", e.what());
        #endif
        throw e;
    }
}

bool NotifyQueue::add_notify(Notify_ptr notify)noexcept {
    notify_queue.push_back(move(notify));
    return true;
}

bool NotifyQueue::send_notify(int socket_fd) {
    json response;
    response["response_type"]=NOTIFY;
    response["result"]=0;
    response["msg"]="消息通知";
    json notify_queue;
    notify_queue=this->serialize();
    response["notify_queue"]=notify_queue;

    ResponseClient(socket_fd,response);
    return true;
}

void NotifyQueue::unserialize(json& j) {
    try{
        this->notify_type=j["notify_type"].get<NotifyType>();
        for(auto& notify_json:j["notify_queue"]){
            auto notify=create_notify(notify_json);
            this->notify_queue.push_back(move(notify));
        }
    }
    catch(exception& e){
        syslog(LOG_ERR, "NotifyQueue unserialize error:%s", e.what());
        #ifdef DEBUG
        PRINT_ERRNO_AND_STRERROR(errno, "NotifyQueue unserialize error:%s", e.what());
        #endif
        throw e;
    }
}

json NotifyQueue::serialize() {
    json notify_queue_json;

    notify_queue_json["notify_type"]=this->notify_type;
    notify_queue_json["notify_queue"] = json::array();

    for(auto& notify:notify_queue){
        notify_queue_json["notify_queue"].push_back(notify->serialize());
    }
    return notify_queue_json;
}

NotifyType NotifyQueue::get_notify_type() const {
    return this->notify_type;
}

